// pages/schoolCate/schoolCate.js
const app = getApp();
import { schoolcart, scartDel, scartEdit } from '../../config/https.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart_nums: 0, // 购物车数量
    useNew: true,
    isNone: false, // 是否为空
    noMore: false, // 没有更多
    list: [], // 列表
    info: '', // 所有数据
    page: 1,
    pagesize: 6,
    category: [], // 一级分类
    category_id: -999, // 一级分类id
    second_cate: [], // 二级分类前四个
    second_cate_len: 0, // 二级分类长度
    second_cate_all: [], // 二级分类所有
    all: false, // 是否展示所有二级分类
    second_cate_id: 0, // 二级分类id（未传默认显示一级分类全部）
    sales_order: '', // 销量排序
    price_order: '', // 1价格降序 2价格升序
    comprehensive_order: '', // 1综合排序
    keyword: '', // 搜索关键词
    //为空提示
    emptyTip: {
      font: "目前还没有商品哦~",
      imgUrl: "/assets/img/no_goods.png"
    },
    // 规格弹窗
    showSpec: false, // 是否展示规格弹窗
    selectGoodsInfos: '', // 当前多规格商品信息
    specInfo: '', // 最终规格信息
    specList: '', // 规格信息
    selectSpecId: '', // 选中规格id
    buyNum: 1, // 购买数量
    height: 'calc(100vh - 170rpx)', // 购买数量
    showCart: false, // 是否展示购物车弹窗
    once: true, // 防止重复提交
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      schoolId: options.id,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('allCate')) {
      this.setData({
        category_id: wx.getStorageSync('allCate'),
      })
      wx.removeStorageSync('allCate');
    }
    this.setData({
      cart_nums: Number(wx.getStorageSync('cart_nums'))
    })
    this.initData();
    this.getData();
  },

  // 获取购物车数量
  getCarts(cb) {
    let that = this;
    this.initData();
    schoolcart({
      token: app.globalData.userId ? app.globalData.userId : '',
      page: 1,
      pagesize: this.data.pagesize,
      category_id: this.data.category_id == -999 ? '' : this.data.category_id,
      second_cate_id: this.data.second_cate_id,
      sales_order: this.data.sales_order,
      price_order: this.data.price_order,
      comprehensive_order: this.data.comprehensive_order,
      keyword: this.data.keyword,
      school_id: this.data.schoolId
    }).then(res => {
      if (res.code == 1) {
        that.setData({
          info: res.data,
          category: res.data.cate_list,
          second_cate_all: res.data.second_cate_list,
          second_cate_len: res.data.second_cate_list.length,
          // 默认选择第一个
          category_id: that.data.category_id ? that.data.category_id : res.data.cate_list[0].id,
          second_cate_id: that.data.second_cate_id ? that.data.second_cate_id : res.data.second_cate_list[0].id,
          cartData: res.data.ShopingCart,
        })

        // 判断加载二级菜单
        if (that.data.useNew) {
          that.setData({
            second_cate: res.data.second_cate_list.slice(0, 4),
          })
        }
        // 判断加载商品
        if (res.data.list.length > 0) {
          that.setData({
            list: [...that.data.list, ...res.data.list],
            noMore: Number(res.data.list.length) >= Number(that.data.pagesize) ? false : true,
          })
        } else {
          that.setData({
            noMore: true
          })
        }

        if (that.data.list.length > 0) {
          that.setData({
            isNone: false
          })
        } else {
          that.setData({
            isNone: true
          })
        }

        typeof cb == 'function' && cb();
      }else{
        that.setData({
          noMore: true
        })
      }
    })
  },

  // 获取数据
  getData() {
    let that = this;
    app.loading();
    wx.request({
      url: app.baseURL + 'item/getItemLists',
      data: {
        token: app.globalData.userId ? app.globalData.userId : '',
        page: this.data.page,
        pagesize: this.data.pagesize,
        category_id: this.data.category_id == -999 ? '' : this.data.category_id,
        second_cate_id: this.data.second_cate_id,
        // second_cate_id: this.data.second_cate_id == 9999 ? '' : this.data.second_cate_id,
        sales_order: this.data.sales_order,
        price_order: this.data.price_order,
        comprehensive_order: this.data.comprehensive_order,
        keyword: this.data.keyword,
        school_id: this.data.schoolId
      },
      success(data) {
        let res = data.data;
        wx.hideLoading();
        if (res.code == 1) {
          that.setData({
            info: res.data,
            category: res.data.cate_list,
            second_cate_all: res.data.second_cate_list,
            second_cate_len: res.data.second_cate_list.length,
            // 默认选择第一个
            category_id: that.data.category_id ? that.data.category_id : res.data.cate_list[0].id,
            second_cate_id: that.data.second_cate_id ? that.data.second_cate_id : res.data.second_cate_list[0].id,
            cartData: res.data.ShopingCart,
          })
          // 判断加载二级菜单
          if (that.data.useNew) {
            that.setData({
              second_cate: res.data.second_cate_list.slice(0, 4),
            })
          }
          // 判断加载商品
          if (res.data.list.length > 0) {
            that.setData({
              list: [...that.data.list, ...res.data.list],
              noMore: Number(res.data.list.length) >= Number(that.data.pagesize) ? false : true,
            })
          } else {
            that.setData({
              noMore: true
            })
          }

          if (that.data.list.length > 0) {
            that.setData({
              isNone: false
            })
          } else {
            that.setData({
              isNone: true
            })
          }

        } else {
          app.$tip(res.msg);
        }

      }
    })
  },

  // 格式化数据
  initData() {
    this.setData({
      list: [],
      page: 1,
    })
  },

  loadMore() {
    if (!this.data.noMore) {
      this.setData({
        page: this.data.page + 1
      })
      this.getData();
    }
  },

  // 去搜索页
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search?schoolId='+this.data.schoolId,
    })
  },

  // 选择一级分类id
  selcetCategory(e) {
    -999
    if (e.currentTarget.dataset.id == -999) {
      this.setData({
        height: 'calc(100vh - 170rpx)'
      })
    } else {
      this.setData({
        height: 'calc(100vh - 460rpx)'
      })
    }
    this.setData({
      category_id: e.currentTarget.dataset.id,
      second_cate_id: ''
    })
    this.initData();
    this.getData();
  },

  // 选择二级分类id
  selcetSecond(e) {
    this.setData({
      second_cate_id: e.currentTarget.dataset.id
    })
    this.initData();
    this.getData();
  },

  // 展示所有二级分类
  showAll() {
    this.setData({
      all: true
    })
  },

  // 所有二级分类里面的选择事件
  selcetAllSecond(e) {
    this.setData({
      useNew: false
    })
    // 拿到当前点击的列
    let item = e.currentTarget.dataset.item, indata = false, old = this.data.second_cate;
    // 判断当前列是否在默认展示的数组里 不在就加到展示的数组中
    old.forEach((items) => {
      if (item.id == items.id) {
        indata = true;
      }
    })
    // 添加当前菜单到展示数据里
    if (!indata) {
      old[1] = item;
      this.setData({
        second_cate: old
      })
    }
    this.setData({
      second_cate_id: e.currentTarget.dataset.id,
      all: false
    })
    this.initData();
    this.getData();

  },

  // 隐藏所有分类
  closeAll() {
    this.setData({
      all: false
    })
  },

  // 综合排序
  searchAll() {
    this.setData({
      comprehensive_order: 1,
      sales_order: '',
      price_order: ''
    })
    this.initData();
    this.getData();
  },

  // 销量排序
  searchSales() {
    this.setData({
      comprehensive_order: '',
      sales_order: 1,
      price_order: ''
    })
    this.initData();
    this.getData();
  },

  // 价格排序
  searchPrices() {
    // 默认降序
    if (!this.data.price_order) {
      this.setData({
        comprehensive_order: '',
        sales_order: '',
        price_order: 1
      })
      this.initData();
      this.getData();
      return
    }
    // 切换升序
    if (this.data.price_order == 1) {
      this.setData({
        comprehensive_order: '',
        sales_order: '',
        price_order: 2
      })
      this.initData();
      this.getData();
      return
    }
    // 切换降序
    if (this.data.price_order == 2) {
      this.setData({
        comprehensive_order: '',
        sales_order: '',
        price_order: 1
      })
      this.initData();
      this.getData();
      return
    }
  },

  // 去普通商品详情
  toDetail(e) {
    wx.navigateTo({
      url: '/pages/school_detail/school_detail?id=' + e.currentTarget.dataset.id + '&school=' + this.data.schoolId,
    })
  },

  // 加入购物车
  addinCart(e) {
    // 未登陆
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    }

    // app.loading();
    let that = this;
    wx.request({
      url: app.baseURL + 'item/addShopingCart',
      data: {
        goods_id: e.currentTarget.dataset.goodsid,
        num: 1,
        goods_spec_id: e.currentTarget.dataset.specid,
        type: 1,
        token: app.globalData.userId
      },
      success(data) {
        let res = data.data;
        // wx.hideLoading();
        if (res.code == 1) {
          // app.$tip('加入购物车成功!');
          // setTimeout(() =>{
          that.getCarts();
          // that.initData();
          // that.getData();
          // },1500)
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 数量加减
  // 加
  addNumber(e) {
    // 下标、数量、购物车id
    let findex = e.currentTarget.dataset.findex,
      id = e.currentTarget.dataset.cartid,
      that = this;
    // app.loading();
    wx.request({
      url: app.baseURL + 'item/addShopingCartNums',
      data: {
        token: app.globalData.userId,
        id: id,
        num: 1,
        type: 1
      },
      success(data) {
        let res = data.data;
        // wx.hideLoading();
        if (res.code == 1) {
          that.getCarts();
          // that.initData();
          // that.getData();
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },
  // 减
  cutNumber(e) {
    // 下标、数量
    let nums = e.currentTarget.dataset.nums,
      id = e.currentTarget.dataset.cartid,
      that = this;
    // if (nums == 1) {
    //   app.$tip('购买数量不能少于1!')
    //   return
    // }
    // app.loading();
    wx.request({
      url: app.baseURL + 'item/addShopingCartNums',
      data: {
        token: app.globalData.userId,
        id: id,
        num: 1,
        type: 2
      },
      success(data) {
        let res = data.data;
        // wx.hideLoading();
        if (res.code == 1) {
          that.getCarts();
          // that.initData();
          // that.getData();
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 多规格商品选择规格
  selectGuige(e) {
    // 未登陆
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    }
    app.loading();
    let that = this;
    wx.request({
      url: app.baseURL + 'item/getGoodsSpec',
      data: {
        goods_id: e.currentTarget.dataset.id,
        school_id: that.data.schoolId
      },
      success(data) {
        let res = data.data;
        wx.hideLoading();
        if (res.code == 1) {
          let arr = [];
          res.data.info.item_sku.forEach((item) => {
            // item.specId = ''
            item.specId = item.sub[0].id;
            arr.push(item.sub[0].id);
          })
          that.setData({
            selectGoodsInfos: e.currentTarget.dataset.item,
            specList: res.data.info.item_sku,
            showSpec: true,
            goods_id: e.currentTarget.dataset.id
          })
          that.getSpecInfo(arr.join('_'))
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 选择规格
  choose(e) {
    let arr = [];
    // 父集下标
    let findex = e.currentTarget.dataset.findex;
    let old = this.data.specList;
    // 改变当前规格选中的规格id
    old[findex].specId = e.currentTarget.dataset.id;
    this.setData({
      specList: old
    })
    this.data.specList.forEach((item) => {
      if (item.specId) {
        arr.push(item.specId)
      }
    })
    this.getSpecInfo(arr.join('_'))
  },

  // 获取选中的规格的信息
  getSpecInfo(id) {
    let that = this;
    wx.request({
      url: app.baseURL + 'item/getItemSku',
      data: {
        goods_id: that.data.goods_id,
        sku_id: id,
        school_id: that.data.schoolId
      },
      success(data) {
        let res = data.data;
        if (res.code == 1) {
          that.setData({
            specInfo: res.data,
            selectSpecId: res.data.goods_spec_id
          })
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 加
  addNums() {
    // 判断库存
    if (Number(this.data.buyNum) <= Number(this.data.specInfo.stock_num)) {
      this.setData({
        buyNum: Number(this.data.buyNum) + 1
      })
    } else {
      app.$tip('不能大于库存!');
    }
  },

  // 减
  cutNums() {
    if (Number(this.data.buyNum) > 1) {
      this.setData({
        buyNum: Number(this.data.buyNum) - 1
      })
    } else {
      app.$tip('最少购买一件!');
    }
  },

  // 关闭弹窗
  closeBuy() {
    this.setData({
      showSpec: false
    })
  },

  // 去确认订单页
  toPlaceorder() {
    let that = this;
    if (!this.data.selectSpecId) {
      app.$tip('请选择规格!');
      return
    }
    // 加入购物车
    app.loading();
    wx.request({
      url: app.baseURL + 'item/addShopingCart',
      data: {
        goods_id: that.data.goods_id,
        num: that.data.buyNum,
        goods_spec_id: that.data.selectSpecId,
        type: 1, // 1正常商品 2秒杀 3特价
        token: app.globalData.userId,
        school_id: this.data.schoolId
      },
      success(suc) {
        wx.hideLoading();
        if (suc.data.code == 1) {
          app.$tip('加入购物车成功!');
          that.getCarts();
          that.setData({
            goods_id: '',
            buyNum: 1,
            selectSpecId: '',
            selectGoodsInfos: '',
            specList: [],
            showSpec: false,
          })
        } else {
          app.$tip(suc.data.msg);
        }
      }
    })
  },

  // 购物车弹窗 显示隐藏
  closePopup(){
    if (this.data.cartData.total_num < 1) {
      return
    }
    this.setData({
      showCart: !this.data.showCart
    })
  },

  // 清空购物车
  clearCart(e){
    let that = this ,ids = e.currentTarget.dataset.ids;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要清空购物车吗?',
      confirmText: '清空',
      confirmColor: '#57B127',
      success(suc){
        if(suc.confirm){
          scartDel({
            token: app.globalData.userId,
            ids: ids
          }).then(res =>{
            if(res.code == 1){
              that.getCarts();
              that.setData({
                showCart: false
              })
            }else{
              app.$tip(res.msg)
            }
          })
        }else if(suc.cancel){
        }
      }
    })
  },

  // 阻止事件冒泡
  nothing(){
  },

  // 购物车弹窗数量变化
  // 减
  cartCut(e){
    let item = e.currentTarget.dataset.item, that = this, index = e.currentTarget.dataset.index;
    if(!this.data.once){
      return
    }
    this.setData({
      once: false
    })
    if (item.num == 1) {
      scartDel({
        token: app.globalData.userId,
        ids: item.id,
        school_id: that.data.schoolId
      }).then(res => {
        that.setData({
          once: true
        })
        if (res.code == 1) {
          that.getCarts(() =>{
            if (that.data.cartData.total_num < 1){
              that.setData({
                showCart: false,
              })
            }
          });
        } else {
          app.$tip(res.msg)
        }
      })
    }else{
      scartEdit({
          token: app.globalData.userId,
          id: item.id,
          num: 1,
          type: 2, // 1加 2减
          school_id: that.data.schoolId
      }).then(res => {
        that.setData({
          once: true
        })
        if (res.code == 1) {
          that.getCarts();
        } else {
          app.$tip(res.msg)
        }
      })
    }
  },

  // 加
  cartAdd(e){
    let item = e.currentTarget.dataset.item, that = this, index = e.currentTarget.dataset.index;
    if (!this.data.once) {
      return
    }
    this.setData({
      once: false
    })
    scartEdit({
      token: app.globalData.userId,
      id: item.id,
      num: 1,
      type: 1, // 1加 2减,
      school_id: that.data.schoolId
    }).then(res => {
      that.setData({
        once: true
      })
      if (res.code == 1) {
        that.getCarts();
      } else {
        app.$tip(res.msg)
      }
    })
  },

  // 结算
  toBuy() {
    if (!this.data.cartData.shoping_cart_ids){
      app.$tip('请先选择商品!');
      return
    }
    let data = {
      ids: this.data.cartData.shoping_cart_ids,
      type: 1,
      school_id: this.data.schoolId
    }
    wx.navigateTo({
      url: '/pages/confirm_order/confirm_order?data=' + JSON.stringify(data) + '&from=cart',
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})